﻿Imports System.Windows
Imports System.Windows.Input
Imports System.Collections.Generic


''' <summary> 
''' This code originated with Bill Reiss and BlueRoseGames 
''' http://www.bluerosegames.com 
''' </summary> 
Public Class KeyHandler
    Private isPressed As New Dictionary(Of Key, Boolean)()
    Private targetElement As FrameworkElement = Nothing
    Public Sub ClearKeyPresses()
        isPressed.Clear()
    End Sub

    Public Sub New(ByVal target As FrameworkElement)
        ClearKeyPresses()
        targetElement = target
        AddHandler target.KeyDown, AddressOf target_KeyDown
        AddHandler target.KeyUp, AddressOf target_KeyUp
        AddHandler target.LostFocus, AddressOf target_LostFocus
    End Sub

    Private Sub target_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        If Not isPressed.ContainsKey(e.Key) Then
            isPressed.Add(e.Key, True)
        End If
    End Sub

    Private Sub target_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs)
        If isPressed.ContainsKey(e.Key) Then
            isPressed.Remove(e.Key)
        End If
    End Sub

    Private Sub target_LostFocus(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ClearKeyPresses()
    End Sub

    Public Function IsKeyPressed(ByVal k As Key) As Boolean
        Return isPressed.ContainsKey(k)
    End Function
End Class
